package com.questions.helper;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.questions.helper.application.QuestionsHelperApplication;
import com.questions.helper.service.MyPoiService;
import com.questions.helper.service.QuestionsHelperService;
import com.questions.helper.view.DrawingView;

import java.util.List;

import xyz.xxin.fileselector.FileSelector;
import xyz.xxin.fileselector.beans.FileBean;
import xyz.xxin.fileselector.interfaces.OnResultCallbackListener;

public class MainActivity extends AppCompatActivity {



    boolean floatingXRun = false;
    QuestionsHelperApplication questionsHelperApplication;
    //声明一个内部广播实例
    ActivityServiceNeedBroadcastReceiver broadcastReceiver;
    Button infile;
    boolean runJob = false;
    Dialog alertDialog;
    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_SERVICE_NEED);
        filter.addAction(ACTION_SERVICE_NEED_NULL);
        filter.addAction(ACTION_SERVICE_TOAST);
        filter.addAction(ACTION_SERVICE_MOVE);
        filter.addAction(ACTION_SERVICE_CLEAR_CANVAS);
        broadcastReceiver = new ActivityServiceNeedBroadcastReceiver();
        registerReceiver(broadcastReceiver, filter);
        questionsHelperApplication = QuestionsHelperApplication.questionsHelperApplication;
        setContentView(R.layout.activity_main);
        Button start = findViewById(R.id.start);
        start.setOnClickListener(v -> {
            if (!floatingXRun)
                checkPermissions();
            Toast.makeText(MainActivity.this, "开始识别", Toast.LENGTH_SHORT).show();
            Log.i("信息", "开始识别");
        });
        infile = findViewById(R.id.infile);
        infile.setOnClickListener(v -> FileSelector.create(this)
                .addDisplayType("xlsx")    // 仅显示指定类型文件
                .isSingle(true)     // 设置为单选模式
                .forResult(new OnResultCallbackListener() {
                    @Override
                    public void onResult(List<FileBean> result) {
                        if (result.isEmpty()) {
                            Toast.makeText(MainActivity.this, "取消选择文件", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        // 文件处理逻辑
                        FileBean fileBean = result.get(0);
                        Toast.makeText(MainActivity.this, fileBean.getName(), Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(MainActivity.this, MyPoiService.class);
                        intent.putExtra("file", fileBean.getFile().getPath());
                        startService(intent);
                        infile.setEnabled(false);
                        AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
                        dialog.setView(R.layout.alert_dialogder);
                        dialog.setMessage(fileBean.getName()+"导入中");
                        alertDialog = dialog.show();
                    }

                    @Override
                    public void onCancel() {
                        Toast.makeText(MainActivity.this, "取消选择文件", Toast.LENGTH_SHORT).show();
                    }
                }));
        Button button = findViewById(R.id.defile);
        button.setOnClickListener((v -> {
            QuestionsHelperApplication.questionsHelperApplication.getLegalknowledgeSQLite().delFile();
            Toast.makeText(MainActivity.this, "题库清空成功", Toast.LENGTH_SHORT).show();

        }));
        Button access = findViewById(R.id.access);
        access.setOnClickListener(v-> {
            Intent intent = new Intent(getApplicationContext(), MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            // 结束当前进程
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(1);
        });
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (!QuestionsHelperService.isServiceEnabled(this)) {
            showOpenAccessibilityServiceDialog();
        }

    }
    View floatingView;
    DrawingView drawingView;
    @SuppressLint("InflateParams")
    private void checkPermissions() {
        if (!Settings.canDrawOverlays(this)) {
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
            startActivity(intent);
        } else {
            floatingView = LayoutInflater.from(this).inflate(R.layout.layout_answer_widget, null);
            drawingView = floatingView.findViewById(R.id.drawingView);
            // 设置 WindowManager 参数
            final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                    30,
                    WindowManager.LayoutParams.MATCH_PARENT,
                    WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
                    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
                            WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN |
                            WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS |
                            WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL| // 允许触摸事件穿透
                            WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE ,
                    PixelFormat.TRANSLUCENT);

            // 初始位置 - 左上角
            params.gravity = Gravity.TOP | Gravity.START;
            params.x = 0;
            // 获取 WindowManager 并添加 View
            WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
            windowManager.addView(floatingView, params);
        }
    }

    private Dialog mTipsDialog;

    public void showOpenAccessibilityServiceDialog() {
        Dialog dialog = this.mTipsDialog;
        if (dialog == null || !dialog.isShowing()) {
            @SuppressLint("InflateParams")
            ImageView imageView = new ImageView(this);
            imageView.setImageResource(R.drawable.open_service_tips);
            imageView.setAdjustViewBounds(true); // 关键：根据图片调整边界
            imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
            imageView.setOnClickListener(v->openAccessibilityServiceSettings());
            AlertDialog.Builder builder = getBuilder(imageView);
            this.mTipsDialog = builder.show();
        }else {
            dialog.show();
        }
    }

    public void openAccessibilityServiceSettings() {
        startActivity(new Intent("android.settings.ACCESSIBILITY_SETTINGS"));
    }

    private AlertDialog.Builder getBuilder(View inflate) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("必须开启辅助服务才能正常使用");
        builder.setView(inflate);
        builder.setPositiveButton("去打开辅助服务", (dialogInterface, i) -> openAccessibilityServiceSettings());
        return builder;
    }

    //声明一个操作常量字符串
    public static final String ACTION_SERVICE_NEED = "action.Service.need";
    public static final String ACTION_SERVICE_NEED_NULL = "action.Service.null";
    public static final String ACTION_SERVICE_TOAST = "action.Service.toast";
    public static final String ACTION_SERVICE_MOVE = "action.ServiceN.move";
    public static final String ACTION_SERVICE_CLEAR_CANVAS = "action.canvas.clear.canvas";

    public static final String TOAST_DATA = "TOAST_DATA";
    public static final String MOVE_DATA = "MOVE_DATA";

    private class ActivityServiceNeedBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action==null||action.isEmpty()){
                return;
            }
            switch ( action){
               case MainActivity.ACTION_SERVICE_NEED:
                   alertDialog.dismiss(); // 隐藏对话框
                   infile.setEnabled(true);
                   Toast.makeText(MainActivity.this, "数据导入成功", Toast.LENGTH_SHORT).show();
                   break;
               case MainActivity.ACTION_SERVICE_NEED_NULL:
                   alertDialog.dismiss(); // 隐藏对话框
                   infile.setEnabled(true);
                   Toast.makeText(MainActivity.this, "数据导入失败", Toast.LENGTH_LONG).show();
                   break;
               case MainActivity.ACTION_SERVICE_TOAST:
                   String message = intent.getStringExtra(MainActivity.TOAST_DATA);
                   Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
                   break;
                case MainActivity.ACTION_SERVICE_MOVE:
                    String tes = intent.getStringExtra(MainActivity.MOVE_DATA);
                    if(tes==null||tes.isEmpty()){
                        return;
                    }
                    String[] data = tes.split(",");
                    for(String s:data){
                        drawingView.moveTo(10f,Float.parseFloat(s)+50f);
                    }
                    break;
                case MainActivity.ACTION_SERVICE_CLEAR_CANVAS:
                    drawingView.clearCanvas();
                    break;

            }
        }
    }
}